from flask import Flask, jsonify
from flask_cors import CORS
import logging
import os
import time
from typing import Optional
from ..config import get_config
from .models import ConversationManager
from .utils import APIError

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def create_app(config_name: Optional[str] = None) -> Flask:
    """创建并配置 Flask 应用"""
    app = Flask(
        __name__,
        template_folder="../../frontend/templates",
        static_folder="../../frontend/static"
    )
    
    config = get_config(config_name)
    app.config.from_object(config)
    
    # 配置CORS
    CORS(app, resources={
        r"/api/*": {
            "origins": app.config['CORS_ORIGINS'],
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization"]
        }
    })
    
    # 初始化数据目录
    data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    app.config['DATA_DIR'] = data_dir

    # 会话数据文件
    conversations_file = os.path.join(data_dir, 'conversations.json')
    app.config['CONVERSATIONS_FILE'] = conversations_file
    
    # 初始化会话管理器
    with app.app_context():
        manager = ConversationManager()
        if os.path.exists(conversations_file):
            manager = ConversationManager.load_from_file(conversations_file)
            logger.info("Loaded conversation data from file")
        app.config['CONVERSATION_MANAGER'] = manager
    
    # 注册错误处理器
    @app.errorhandler(APIError)
    def handle_api_error(error):
        return jsonify({
            "error": "API Error",
            "message": str(error)
        }), error.status_code

    @app.errorhandler(404)
    def handle_404(error):
        return jsonify({
            'error': 'Not Found',
            'message': '请求的资源不存在'
        }), 404

    @app.errorhandler(500)
    def handle_500(error):
        logger.error(f"Internal server error: {str(error)}")
        return jsonify({
            'error': 'Internal Server Error',
            'message': '服务器内部错误'
        }), 500

    # 定期保存数据
    @app.before_request
    def before_request():
        app.config['LAST_ACTIVITY'] = time.time()

    @app.after_request
    def after_request(response):
        # 每5分钟保存一次数据
        last_activity = app.config.get('LAST_ACTIVITY', 0)
        if time.time() - last_activity > 300:  # 5分钟
            try:
                manager = app.config.get('CONVERSATION_MANAGER')
                if manager:
                    manager.save_to_file(app.config['CONVERSATIONS_FILE'])
                    logger.info("Saved conversation data to file (timed)")
            except Exception as e:
                logger.error(f"Error saving conversation data: {str(e)}")
        return response

    from .routes import main as main_blueprint
    app.register_blueprint(main_blueprint)

    logger.info("Application initialized successfully")
    return app
